//
//  copy-on-write-demo.swift
//  Underlying-MemoryManagement
//
//  Created by jianbo.pei on 2023/12/9.
//

import Foundation

func print(address o: UnsafeRawPointer ) {
    print(String(format: "%p", Int(bitPattern: o)))
}

func printPoint<T>(ptr: UnsafePointer<T>) {
    print(ptr)
}

func test_copy() {
    let a = [1, 2]
    let b = a
    print("111---start")
    print(address: a)
    print(address: b)
    print("111---end")
    
    /**
     111---start
     0x6000013b04a0
     0x6000013b04a0
     111---end
     */
}

func test_copyOnWrite_1() {
    var a = [1, 2]
    let b = a
    print("\n222---start")
    print(address: a)
    print(address: b)
    print("222---end")
    a.append(3)
    
    print("333---start")
    print(address: a)
    print(address: b)
    print("333---end")
    
    /**
     222---start
     0x6000013b04a0
     0x6000013b04a0
     222---end
     333---start
     0x6000008b0160
     0x6000013b04a0
     333---end
     */
}

func test_copyOnWrite_2() {
    let a = [1, 2]
    var b = a
    print("\n444---start")
    print(address: a)
    print(address: b)
    print("444---end")
    b.append(3)
    
    print("555---start")
    print(address: a)
    print(address: b)
    print("555---end")
    
    /**
     444---start
     0x6000013b04a0
     0x6000013b04a0
     444---end
     555---start
     0x6000013b04a0
     0x6000008b4020
     555---end
     */
}

func test_cow_int() {
    var a = 3
    var b = a
    printPoint(ptr: &a)
    printPoint(ptr: &b)
}
